//
//  UIView+SPExtension.m
//  EMarket
//
//  Created by 石头 on 2018/5/8.
//  Copyright © 2018年 好日子. All rights reserved.
//

#import "UIView+SPExtension.h"

@implementation UIView (SPExtension)


- (CGFloat)sp_x
{
    return self.frame.origin.x;
}
- (void)setSp_x:(CGFloat)sp_x
{
    CGRect spFrame = self.frame;
    spFrame.origin.x = sp_x;
    self.frame = spFrame;
}

-(CGFloat)sp_y
{
    return self.frame.origin.y;
}
-(void)setSp_y:(CGFloat)sp_y
{
    CGRect spFrame = self.frame;
    spFrame.origin.y = sp_y;
    self.frame = spFrame;
}

-(CGPoint)sp_origin
{
    return self.frame.origin;
}
-(void)setSp_origin:(CGPoint)sp_origin
{
    CGRect spFrame = self.frame;
    spFrame.origin = sp_origin;
    self.frame = spFrame;
}

-(CGFloat)sp_width
{
    return self.frame.size.width;
}
-(void)setSp_width:(CGFloat)sp_width
{
    CGRect spFrame = self.frame;
    spFrame.size.width = sp_width;
    self.frame = spFrame;
}

-(CGFloat)sp_height
{
    return self.frame.size.height;
}
-(void)setSp_height:(CGFloat)sp_height
{
    CGRect spFrame = self.frame;
    spFrame.size.height = sp_height;
    self.frame = spFrame;
}

-(CGSize)sp_size
{
    return self.frame.size;
}
- (void)setSp_size:(CGSize)sp_size
{
    CGRect spFrame = self.frame;
    spFrame.size = sp_size;
    self.frame = spFrame;
}

-(CGFloat)sp_centerX{
    
    return self.center.x;
}

-(void)setSp_centerX:(CGFloat)sp_centerX{
    
    CGPoint dcFrmae = self.center;
    dcFrmae.x = sp_centerX;
    self.center = dcFrmae;
}

-(CGFloat)sp_centerY{
    
    return self.center.y;
}

-(void)setSp_centerY:(CGFloat)sp_centerY{
    
    CGPoint spFrame = self.center;
    spFrame.y = sp_centerY;
    self.center = spFrame;
}

- (CGFloat)sp_right{
    
    return CGRectGetMaxX(self.frame);
}

- (CGFloat)sp_bottom{
    
    return CGRectGetMaxY(self.frame);
}

- (void)setSp_right:(CGFloat)sp_right{
    
    self.sp_x = sp_right - self.sp_width;
}

- (void)setSp_bottom:(CGFloat)sp_bottom{
    
    self.sp_y = sp_bottom - self.sp_height;
}

- (BOOL)intersectWithView:(UIView *)view{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect selfRect = [self convertRect:self.bounds toView:window];
    CGRect viewRect = [view convertRect:view.bounds toView:window];
    return CGRectIntersectsRect(selfRect, viewRect);
}

- (BOOL)isShowingOnKeyWindow {
    // 主窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    // 以主窗口左上角为坐标原点, 计算self的矩形框
    CGRect newFrame = [keyWindow convertRect:self.frame fromView:self.superview];
    CGRect winBounds = keyWindow.bounds;
    
    // 主窗口的bounds 和 self的矩形框 是否有重叠
    BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
    
    return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;
}

+(instancetype)sp_viewFromXib
{
    return [[NSBundle mainBundle]loadNibNamed:NSStringFromClass(self) owner:nil options:nil].firstObject;
}


@end
